/*
 * @Author: zi.yang
 * @Date: 2022-12-03 00:56:50
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-12-03 15:29:17
 * @Description: 工厂函数
 * @FilePath: /promise/lib/createPromiseInstance.ts
 */
import { getType, isPromise } from './common';
import { throwTypeError, useThrowIsNotFunction } from './throwError';

/**
 * 创建并生成 Promise 实例
 * @param { ToyPromiseConstructor } ToyPromise
 * @returns { PromiseInstanceType }
 */
function createPromiseInstance(ToyPromise: ToyPromiseConstructor): PromiseInstanceType {
  // ES262-25.4.4.1 Promise.all( iterable ) throws if 'this' is not a Promise constructor:
  if (!isPromise(ToyPromise)) {
    throw throwTypeError(`#<${getType(ToyPromise)}> is not a Promise constructor`);
  }
  const promiseInstance = <PromiseInstanceType>{};
  const toyPromise = new ToyPromise((resolve, reject) => {
    // ES262-25.4.1.6.1 step 9 invalid 'reject' throws TypeError with Promise.then:
    useThrowIsNotFunction(resolve, reject);
    promiseInstance.resolveHook = resolve;
    promiseInstance.rejectHook = reject;
  });
  promiseInstance.Instance = toyPromise;
  return promiseInstance;
}

export default createPromiseInstance;
